module bram_updater(
    input sys_rst_n,
    // FT232H
    input usb_clk_60m,
    input [7:0] usb_data,
    input usb_rxf_n,
    output reg usb_oe_n,
    output reg usb_rd_n,
    // rom
    output reg [10:0] bram_wr_addr,
    output reg [10:0] bram_wr_data,
    output reg bram_wr_en
);

reg usb_oe_n_d1;

always @(posedge usb_clk_60m or negedge sys_rst_n) begin
    if (!sys_rst_n)
        bram_wr_data <= 8'b0;
    else
        bram_wr_data <= usb_data;
end

always @(posedge usb_clk_60m or negedge sys_rst_n) begin
    if (!sys_rst_n)
        bram_wr_addr <= 5'b0;
    else if (bram_wr_en == 1)
        bram_wr_addr <= bram_wr_addr + 8'b1;
    else
        bram_wr_addr <= 5'b0;
end

// control usb_oe_n
always @(posedge usb_clk_60m or negedge sys_rst_n) begin
    if (!sys_rst_n)
        usb_oe_n <= 1'b1;
    else if (!usb_rxf_n)
        usb_oe_n <= 1'b0;
    else
        usb_oe_n <= 1'b1;
end

// delay a clk for usb_oe_n_d1
always @(posedge usb_clk_60m or negedge sys_rst_n) begin
    if (!sys_rst_n)
        usb_oe_n_d1 <= 1'b1;
    else
        usb_oe_n_d1 <= usb_oe_n;
end

always @(*) begin
    if (!sys_rst_n) begin
        usb_rd_n <= 1'b1;
        bram_wr_en <= 1'b0;
    end
    else begin
        usb_rd_n <= usb_oe_n || usb_oe_n_d1;
        bram_wr_en <= ~(usb_oe_n || usb_oe_n_d1);
    end
end

endmodule